from common.libs.Helper import ops_render
from common.models.member import Member
from common.libs.UrlManager import UrlManager
from common.libs.Helper import getCurrentDate
from common.models.member import MemberComment
from common.libs.Helper import getDictFilterFiled
from common.libs.Helper import selectFilterObj
from common.models.food import Food
from common.models.pay import PayOrder
from common.models.pay import PayOrderItem
from flask import request
from flask import Blueprint
from flask import redirect
from sqlalchemy import or_
from application import app
from flask import jsonify
import json

route_member = Blueprint('member_page', __name__)

@route_member.route('/index')
def index():
    query = Member.query
    resp = request.values
    resp_data = {}
    sex = None

    # 混合搜索
    if 'mix_kw' in resp:
        # 性别转换
        if resp['mix_kw'] in ['男', '女', '未知']:
            gender = resp['mix_kw']
            if gender == '男':
                sex = 1
            elif gender == '女':
                sex = 2
            else:
                sex = 0
        rule = or_(
            Member.nickname.like('%{}%'.format(resp['mix_kw'])),  # 昵称搜索
            Member.sex.like('%{}%'.format(sex))  # 性别搜索
        )
        query = query.filter(rule)

    # 搜索状态
    if 'status' in resp and int(resp['status']) > -1:
        query = query.filter(Member.status == resp['status'])

    # 指定当前页码
    page = resp.get('page', type=int)
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    # 创建分页对象
    pagination = query.filter().order_by(Member.id.desc()).paginate(page, page_size, False)

    resp_data['STATUS_LIST'] = app.config['STATUS_MAPPING']
    resp_data['pagination'] = pagination
    resp_data['search_val'] = resp
    resp_data['page_url'] = page_url
    resp_data['current'] = 'index'
    resp_data['placeholder'] = '请输入关键字'

    return ops_render('member/index.html', resp_data)

@route_member.route('/info')
def info():
    resp_data = {}
    # 若不符合，指定重定向的路由
    back_url = UrlManager.buildUrl('/member/index')

    # 通过get请求url上获取的id需要验证处理
    id = request.args.get('id', type=int)
    if id < 1:
        return redirect(back_url)
    member = Member.query.get(id)
    if not member:
        return redirect(back_url)
    # 会员订单
    pay_order_list =PayOrder.query.filter_by(member_id=id)\
        .order_by(PayOrder.id.desc()).limit(20).all()

    # 会员评论
    comment_list = MemberComment.query.filter_by(member_id= id)\
        .order_by(MemberComment.id.desc()).limit(20).all()

    resp_data['current'] = 'index'
    resp_data['member'] = member
    resp_data['pay_order_list'] = pay_order_list
    resp_data['comment_list'] = comment_list
    return ops_render('member/info.html', resp_data)

@route_member.route('/set', methods=['GET', 'POST'])
def set():
    """
    该视图函数用于修改会员信息
    :return:
    """
    resp_data = {}
    result = {'code': 200, 'msg': '操作成功！'}

    if request.method == 'GET':
        back_url = UrlManager.buildUrl('/member/index')
        id = request.args.get('id', type=int)
        if id < 1:
            return redirect(back_url)

        member = Member.query.get(id)
        if not member:
            return redirect(back_url)

        # 被删除的用户不允许修改
        if member.status == 0:
            return redirect(back_url)

        resp_data['member'] = member
        resp_data['current'] = 'index'
        return ops_render('member/set.html', resp_data)

    id = request.values.get('id')
    nickname = request.values.get('nickname')
    if not id:
        result['code'] = -1
        result['msg'] = '请指定修改的用户'
        return jsonify(result)

    member_info = Member.query.get(id)
    if not member_info:
        result['code'] = -1
        result['msg'] = '修改用户不存在'
        return jsonify(result)

    member_info.nickname = nickname
    member_info.update()
    return jsonify(result)

@route_member.route('/cat_ops', methods=['GET', 'POST'])
def ops():
    result = {'code': 200, 'msg': '操作成功！'}
    id = request.values.get('id')
    action = request.values.get('action')

    if not id:
        result['code'] = -1
        result['msg'] = '请指定操作的用户'
        return jsonify(result)

    if action not in ['remove', 'recover']:
        result['code'] = -1
        result['msg'] = '操作异常，请重试！'
        return jsonify(result)

    member = Member.query.get(id)
    if not member:
        result['code'] = -1
        result['msg'] = '删除用户不存在！'
        return jsonify(result)

    if 'remove' == action:
        member.status = 0

    if 'recover' == action:
        member.status = 1

    member.updated_time = getCurrentDate()
    member.update()
    return jsonify(result)

@route_member.route('/comment')
def comment():
    query = MemberComment.query
    resp = request.values
    resp_data = {}

    # 指定当前页码
    page = resp.get('page', type=int)
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    # 分页的路由
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 创建分页对象
    pagination = query.filter().order_by(MemberComment.id.desc()).paginate(page, page_size, False)

    # 构建评论和美食的映射关系
    comment_food_mapping = {}
    comment_list = query.order_by(MemberComment.id.desc()).all()
    for comment in comment_list:
        comment_food_mapping[comment.id] = []
        # 获取评论中美食的订单详情
        pay_order_items = PayOrderItem.query.filter_by(pay_order_id = comment.pay_order_id).all()
        # 生成订单详情中美食的映射关系
        food_ids = selectFilterObj(pay_order_items, 'food_id')
        food_mapping = getDictFilterFiled(Food, Food.id, 'id', food_ids)
        for item in pay_order_items:
            temp_food = food_mapping[item.food_id]
            comment_food_mapping[comment.id].append({temp_food.name: item.quantity})

    # 构建会员和评论的映射关系
    member_ids = selectFilterObj(comment_list, 'member_id')
    comment_member_mapping = getDictFilterFiled(Member, Member.id, 'id', member_ids)

    resp_data['current'] = 'comment'
    resp_data['page_url'] = page_url
    resp_data['pagination'] = pagination
    resp_data['comment_food_mapping'] = comment_food_mapping
    resp_data['comment_member_mapping'] = comment_member_mapping

    return ops_render('member/comment.html', resp_data)
